import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import {useVisionStore, useForceUpdate} from '@/pages/index'
import OpNode from './opNode'
import { mapComTree, mapTree } from './utils';


export default (props:any) => {
  const {opNodeList, components} = useVisionStore();
  const forceUpdate = useForceUpdate();
  const ref= useRef(null)
  const {parentOpNode} = props 
  const [currentOpNode, setCurrentOpNode] =  useState<any>(null)
  useEffect(()=>{
    if(!parentOpNode) return
    let currentOpNode = new OpNode(ref.current, {planAction: props.planAction})
    currentOpNode.setParent(parentOpNode)
    opNodeList.push(currentOpNode)
    currentOpNode.forceUpdate = forceUpdate
    setCurrentOpNode(currentOpNode)
  }, [parentOpNode])

  useEffect(() => {
    // 先构造一个opNode
    if(!parentOpNode) return
    let doms = mapComTree(parentOpNode.dom)
    let opNodes: any[] = []
    mapTree(parentOpNode, (__opNode: any) => {
      opNodes.push(__opNode);
    })

    doms.forEach((dom, i) => {
      let opNode = opNodes[i]
      if(opNode) {
        opNode.dom = dom
      }
    })
  });

  let childRender = []


  if(currentOpNode) {
    let children
    if(currentOpNode.props.comCode) {
      let Component = components[currentOpNode.comCode].render || null
      children = [<Component opNode={currentOpNode}/>]
    }else{
      children = currentOpNode.children.map((pitem:any) => {
        let Component = components[pitem.props.comCode].render || null
        return <Component opNode={pitem}/>
      })
    }
    childRender = children
  }

  const initStyle = {
    display: 'flex',
    width: '100%',
    height: '100%',
  };

  return React.createElement(
    'div',
    {
      ref,
      style: { ...initStyle, ...props.style},
      'data-visplan': props.plan,
      'data-visdata': 'true',
    },
    ...childRender
  );
};
